package com.rx.action.admin;

import java.util.HashSet;
import java.util.Set;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;

import com.rx.action.BaseAction;
import com.rx.biz.BaseBiz;
import com.rx.biz.sys.UserBiz;
import com.rx.entity.sys.Privilege;
import com.rx.entity.sys.Role;
import com.rx.entity.sys.User;
import com.rx.util.PasswordEncoderUtils;

@Namespace("/admin")
@Results( { @Result(name = "index", location = "index.html") })
public class LoginAction extends BaseAction<User, Long> {

	@Resource(name = "userBiz")
	public void setBiz(BaseBiz<User, Long> biz) {
		super.biz = biz;
	}

	@Override
	public String list() throws Exception {
		// 校验账号和密码是否输入
		String userName = getParameter("userName");
		String passWord = getParameter("passWord");
		if (StringUtils.isEmpty(userName) || StringUtils.isEmpty(passWord)) {
			return SUCCESS;
		}
		// 获取用户
		User user = ((UserBiz) biz).findUserByUserNameAndPassWord(userName,
				PasswordEncoderUtils.encodePassword(passWord));
		if (user != null) {
			// 用户信息加入session
			getSession().setAttribute("user", user);
			getSession().setAttribute("currentUserName", user.getUserName());
			// 权限编号集合
			Set<String> privilegeCodes = new HashSet<String>();
			// 权限地址集合
			Set<String> privilegeUrls = new HashSet<String>();
			// 遍历角色
			for (Role role : user.getRoles()) {
				// 遍历权限
				for (Privilege privilege : role.getPrivileges()) {
					// 放入权限编号
					privilegeCodes.add(privilege.getCode());
					// 放入权限地址
					privilegeUrls.add(privilege.getUrl());
				}
			}
			// 权限编号加入session
			getSession().setAttribute("privilege_code", privilegeCodes);
			// 权限地址加入session
			getSession().setAttribute("privilege_url", privilegeUrls);

			return "index";
		}
		addActionMessage("对不起，账号或密码不正确！");
		return SUCCESS;
	}

	@Override
	public String delete() throws Exception {
		return null;
	}

	@Override
	public String input() throws Exception {
		return null;
	}

	@Override
	public String save() throws Exception {
		return null;
	}

}
